package Demo1;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MyLinkedList<E> {
    private int size = 0;

    public static class Node<E>{
        E data;
        Node<E> next;
        public Node(E data, Node<E> next) {
            this.data = data;
            this.next = next;
        }
    }
    //添加数据
    public Node<E> add(){
        Node<E> hand = null;
        Scanner scanner = new Scanner(System.in);
        while (true) {
                System.out.println("请输入数据：");
                String data = scanner.next();
                if (data.equals("exit")) break;
                if (hand == null){
                    hand = new Node(data,null);
                    size++;
                }else {
                    Node<E> temp = hand;
                    while (temp.next != null){
                        temp = temp.next;
                    }
                    temp.next = new Node(data,null);
                    size++;
                }
        }
        return hand;
    }

    //遍历数据
    public void forEach(Node<E> hand){
        if (hand == null){
            System.out.println(hand);
            return;
        }
        while ( hand != null){
            System.out.println(hand.data+" ");
            hand = hand.next;
        }
    }

    //提供 reverse 方法，参数为 hand left right
    public Node<E> reverse(Node<E> head ,int left, int right){

        if (head == null || left < 1 || left > size || right < 1 || right >size || left == right || left >right ){
               return head;
        }
        Node<E> first = head;
        int index = 0;
        List<E> list = new ArrayList<>();
        Node<E> temp = null;
        while (head != null){
            index++;
            if (index == left){
                temp = head;
            }
            if (index > left && index <= right){
                list.add(head.data);
            }
            if (right == index) break;
            head = head.next;
        }
        for (int i = list.size() - 1; i >= 0 ; i--) {
            E e = list.get(i);
            temp.data = e;
            temp = temp.next;

        }
        return first;
    }
}
